sampler2D MainTex : register(S0);

float2 MainTex_TexelSize : register(C0) = float2(0.001, 0.002);
float EdgeAlphaThreshold : register(C1) = 0.9;

float OuterGlowWidth : register(C2) = 0.03;
float4 OuterGlowColor : register(C3) = float4(1, 0, 0, 1);
float OuterGlowAlphaSumThreshold : register(C4) = 0.1; 
 

float InnerGlowWidth : register(C5) = 0.1;
float4 InnerGlowColor : register(C6) = float4(0, 0, 0, 0);
float InnerGlowAlphaSumThreshold : register(C7) = 0.1; 

float GlowRate : register(C8) = 2;
#define GLOWACCURACY 9
struct v2f
{
    float4 vertex : SV_POSITION;
    float2 uv[9] : TEXCOORD0;
};
 
//float CalculateAlphaSumAround(v2f i)
//{
//    float texAlpha;
//    float alphaSum = 0;
//    for (int it = 0; it < 9; it++)
//    {
//        texAlpha = tex2D(MainTex, i.uv[it]).a;
//        alphaSum += texAlpha;
//    }
// 
//    return alphaSum;
//}
float CalculateCircleSumAlpha(float2 origin, float radius, int times)
{
    float sum = 0;
    float perAngle = 360 / times;
    for (int i = 0; i < times; i++)
    {
        float2 newUV = origin + radius * float2(cos(perAngle * i), sin(perAngle * i));
        sum += tex2D(MainTex, newUV).a;
    }
 
    return sum;
}

v2f vert(float2 uv)
{
    v2f o;
 
    o.uv[0] = uv + MainTex_TexelSize.xy * half2(-1, -1);
    o.uv[1] = uv + MainTex_TexelSize.xy * half2(0, -1);
    o.uv[2] = uv + MainTex_TexelSize.xy * half2(1, -1);
    o.uv[3] = uv + MainTex_TexelSize.xy * half2(-1, 0);
    o.uv[4] = uv + MainTex_TexelSize.xy * half2(0, 0);
    o.uv[5] = uv + MainTex_TexelSize.xy * half2(1, 0);
    o.uv[6] = uv + MainTex_TexelSize.xy * half2(-1, 1);
    o.uv[7] = uv + MainTex_TexelSize.xy * half2(0, 1);
    o.uv[8] = uv + MainTex_TexelSize.xy * half2(1, 1);
    return o;
}
 
float4 main(float2 uv : TEXCOORD) : COLOR
{
    v2f i = vert(uv);
    
    float4 orignColor = tex2D(MainTex, i.uv[4]);
    float4 destColor = float4(orignColor.rgba);
    float4 glow = float4(0, 0, 0, 0);
    bool isInner = (orignColor.a >= EdgeAlphaThreshold);
    
    if (OuterGlowWidth > 0)
    {
        float alphaCircleSum = CalculateCircleSumAlpha(i.uv[4], OuterGlowWidth, GLOWACCURACY) / GLOWACCURACY;
        float outerColorAlpha = saturate(alphaCircleSum - OuterGlowAlphaSumThreshold) / (1 - OuterGlowAlphaSumThreshold);
        if (!isInner)
        {
        	glow=float4( 0,0,0,outerColorAlpha);
            destColor = float4(OuterGlowColor.rgb, OuterGlowColor.a * outerColorAlpha);
        }

    }
    if (InnerGlowWidth > 0)
    {
        float alphaCircleSum = CalculateCircleSumAlpha(i.uv[4], InnerGlowWidth, GLOWACCURACY) / GLOWACCURACY;
        float innerColorAlpha = saturate(alphaCircleSum - InnerGlowAlphaSumThreshold) / (1 - InnerGlowAlphaSumThreshold);
        if (isInner)
        {
        	glow=InnerGlowColor;
            destColor = float4(orignColor.rgb, orignColor.a * innerColorAlpha);
        }
            
    }
   
    return lerp(glow*GlowRate, destColor, destColor.a);
}